<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>客户管理</el-breadcrumb-item>
      <el-breadcrumb-item>客户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getCustomersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getCustomersList"
            ></el-button>
          </el-input>
        </el-col>
        <el-button type="primary" @click="addDialogVisible = true"
          >添加客户</el-button
        >
        <el-button type="primary" @click="vipDialogVisible = true"
          >点击查看积分规则</el-button
        >
        <el-button type="primary" @click="exportExcel"
          >点击导出表格数据</el-button
        >
      </el-row>
      <!-- 虚拟表格数据，仅用来导出数据 -->
      <el-table
        :data="customerListforExport"
        border
        stripe
        id="out-table"
        v-show="false"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="客户姓名"
          prop="customer_name"
        ></el-table-column>
        <el-table-column label="手机" prop="customer_phone"></el-table-column>
        <el-table-column label="性别" prop="customer_gender"></el-table-column>
        <el-table-column label="邮箱" prop="customer_email"></el-table-column>
        <el-table-column label="积分" prop="customer_vip_num"></el-table-column>
        <el-table-column label="vip等级" prop="customer_vip">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.customer_vip_num > 8888">
              黑金vip
            </el-tag>
            <el-tag type="danger" v-else-if="scope.row.customer_vip_num > 5888">
              钻石vip
            </el-tag>
            <el-tag
              type="warning"
              v-else-if="scope.row.customer_vip_num > 2888"
            >
              黄金vip
            </el-tag>
            <el-tag v-else-if="scope.row.customer_vip_num > 888">
              白银vip
            </el-tag>
            <el-tag type="success" v-else>
              普通vip
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 表格数据 -->
      <el-table :data="customerList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="客户姓名"
          prop="customer_name"
        ></el-table-column>
        <el-table-column label="手机" prop="customer_phone"></el-table-column>
        <el-table-column label="性别" prop="customer_gender"></el-table-column>
        <el-table-column label="邮箱" prop="customer_email"></el-table-column>
        <el-table-column label="积分" prop="customer_vip_num"></el-table-column>
        <el-table-column label="vip等级" prop="customer_vip">
          <template slot-scope="scope">
            <el-tag type="info" v-if="scope.row.customer_vip_num > 8888">
              黑金vip
            </el-tag>
            <el-tag type="danger" v-else-if="scope.row.customer_vip_num > 5888">
              钻石vip
            </el-tag>
            <el-tag
              type="warning"
              v-else-if="scope.row.customer_vip_num > 2888"
            >
              黄金vip
            </el-tag>
            <el-tag v-else-if="scope.row.customer_vip_num > 888">
              白银vip
            </el-tag>
            <el-tag type="success" v-else>
              普通vip
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.customer_id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.customer_id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </el-card>
    <!-- 添加客户的对话框 -->
    <el-dialog
      title="注册会员"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 内容区 -->
      <el-form
        :model="addForm"
        :rules="customerRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="客户姓名" prop="customer_name" label-width="80px">
          <el-input v-model="addForm.customer_name"></el-input>
        </el-form-item>
        <el-form-item label="客户手机" prop="customer_phone" label-width="80px">
          <el-input v-model="addForm.customer_phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="customer_gender" label-width="80px">
          <el-select v-model="addForm.customer_gender" placeholder="请选择">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="customer_email" label-width="80px">
          <el-input v-model="addForm.customer_email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCustomer"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 修改客户信息的对话框 -->
    <el-dialog
      title="修改客户信息"
      :visible.sync="editDialogVisible"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form
        :model="editForm"
        :rules="customerRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="客户姓名" prop="customer_name" label-width="80px">
          <el-input v-model="editForm.customer_name"></el-input>
        </el-form-item>
        <el-form-item label="客户手机" prop="customer_phone" label-width="80px">
          <el-input v-model="editForm.customer_phone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="customer_gender" label-width="80px">
          <el-select v-model="editForm.customer_gender" placeholder="请选择">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="customer_email" label-width="80px">
          <el-input v-model="editForm.customer_email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCustomerInfo"> 确 定 </el-button>
      </span>
    </el-dialog>
    <!-- 会员积分规则 -->
    <el-dialog
      title="会员积分规则"
      :visible.sync="vipDialogVisible"
      width="22%"
    >
      <h1>达到不同vip所需积分：</h1>
      <p>积分制度（消费一元可以获得1积分，每一笔订单额外+100）</p>
      <p>| 会员等级 | 所需积分 | 会员特权 |</p>
      <p>|普通vip ------- 0 ------- 9.8折 |</p>
      <p>| 白银vip ----- 888 ----- 9.5折 |</p>
      <p>| 黄金vip ---- 2888 ------- 9折 |</p>
      <p>| 钻石vip ---- 5888 ----- 8.8折 |</p>
      <p>| 黑金vip ---- 8888 ------- 8折 |</p>
    </el-dialog>
  </div>
</template>

<script>
// 引入导出Excel表格依赖
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      queryInfo: {
        query: '',
        pageNum: 1,
        pageSize: 10
      },
      // 客户列表
      customerList: [],
      // 客户总数
      total: 0,
      // 控制添加客户对话框的显示与隐藏
      addDialogVisible: false,
      vipDialogVisible: false,
      // 添加客户的表单数据
      addForm: {
        customer_name: '',
        customer_phone: '',
        customer_gender: '',
        customer_email: ''
      },
      // 控制修改客户对话框的显示与隐藏
      editDialogVisible: false,
      customerListforExport: [],
      //修改表单信息
      editForm: {},
      //修改表单的验证规则对象
      customerRules: {
        customer_name: [
          {
            required: true,
            message: '请输入客户姓名',
            trigger: 'blur'
          }
        ],
        customer_phone: [
          {
            required: true,
            message: '请输入客户手机',
            trigger: 'blur'
          }
        ],
        customer_gender: [
          {
            required: true,
            message: '请选择客户性别',
            trigger: 'blur'
          }
        ]
      },
      genderOptions: [
        {
          value: '1',
          label: '男'
        },
        {
          value: '0',
          label: '女'
        }
      ]
    }
  },
  created() {
    this.getCustomersList()
  },
  methods: {
    // 根据分页获取对应的客户列表
    async getCustomersList() {
      const { data: res } = await this.$http.get('allCustomer', {
        params: this.queryInfo
      })
      if (res.numbers < 1) {
        return this.$message.error('获取客户列表失败！')
      }
      this.customerList = res.data
      this.total = res.numbers
      //获取虚拟表格数据
      const { data: res2 } = await this.$http.get('allCustomers')
      this.customerListforExport = res2.data
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getCustomersList()
    },
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getCustomersList()
    },
    // 展示客户编辑的对话框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('getUpdateCustomer?id=' + id)
      if (res == null) {
        return this.$message.error('查询客户信息失败！')
      }
      this.editForm = res
      this.editDialogVisible = true
    },
    // 监听添加客户对话框的关闭事件
    addDialogClosed() {
      // 重置表单项
      this.$refs.addFormRef.resetFields()
    },
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: 'application/octet-stream' }),
          //设置导出文件名称
          '导出数据文件.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    //添加客户
    addCustomer() {
      //发起添加客户请求+
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('addCustomer', this.addForm)
        if (res !== 'success') {
          return this.$message.error('添加客户信息失败')
        }
        this.$message.success('添加客户信息成功')
        // 隐藏添加客户对话框
        this.addDialogVisible = false
        // 重新获取客户列表数据
        this.getCustomersList()
      })
    },
    //修改客户信息并提交
    editCustomerInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        //发起修改客户信息的数据请求
        const { data: res } = await this.$http.put(
          'editCustomer',
          this.editForm
        )
        if (res !== 'success') {
          return this.$message.error('修改数据失败！')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新客户数据列表
        this.getCustomersList()
        //提示修改成功
        this.$message.success('修改数据成功！')
      })
    },
    // 通过Id删除客户
    async removeById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该客户信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete('deleteCustomer?id=' + id)
      if (res !== 'success') {
        return this.$message.error('删除客户信息失败!')
      }
      this.$message.success('删除客户信息成功!')
      this.getCustomersList()
    }
  }
}
</script>

<style lang="less" scoped></style>
